package com.it.emall.controller;


import com.it.emall.constants.FileUploadConstants;
import com.it.emall.utils.ResponseUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 */
@RestController
public class StorageController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/wx/storage/create")
    public Object upload(MultipartFile file){
        if(file != null && !file.isEmpty()){
            //保存目录
            File saveDir = new File(FileUploadConstants.SAVE_DIR);
            if(!saveDir.exists()){//目录不存在就创建
                saveDir.mkdirs();
            }

            //文件名
            String originalFilename = file.getOriginalFilename();
           String filename = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));

           //保存
            File saveFile = new File(saveDir, filename);
            try {
                file.transferTo(saveFile);
                Map<String, Object> data = new HashMap<>();
                data.put("url", FileUploadConstants.SERVER_HOST+ FileUploadConstants.FILE_URL+filename);
                return ResponseUtils.ok(data);
            } catch (IOException e){
                e.printStackTrace();
                return ResponseUtils.fail(1,"文件上传失败");
            }



        }else {
            return ResponseUtils.fail(1,"文件上传为空");
        }
    }
}
